<?php
namespace App\Http\Controllers\Api\v1;

use App\Events\ApproveOperate;
use App\Http\Controllers\Api\BaseController;
use App\Http\Resources\User;
use App\Http\Resources\UserCollection;
use App\Item;
use App\Repositories\UserRepository;
use App\Scopes\StatusScope;
use App\Traits\BaseApiFunc;
use App\Traits\ResetPassword;
use App\User as UserModel;
use Auth;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UserController extends BaseController {

	use BaseApiFunc, ResetPassword;

	protected $model, $page_size;

	public function __construct(UserRepository $user) {
		parent::__construct();

		$this->model = $user;
		$this->page_size = config('blog.admin_page.user_page');
	}

	public function user($name) {
		$list = (new User($this->model->getUserByName($name)->load(['comments' => function ($query) {
			return $query->whereHas("item", function ($query) {
				return $query->has('cate');
			});
		}])->load('messages')))->type('index');
		return $this->response->withSuccess($list);
	}

	public function approve(Item $item) {
		Auth::user()->approveItems()->toggle($item);
		event(new ApproveOperate($item->id));
		return $this->response->withNoContent();
	}

	public function info($name) {
		$list = (new User($this->model->getById(Auth::user()->id)))->type('info');
		return $this->response->withSuccess($list);
	}

	public function initial() {
		$user = Auth::user();
		$list = [
			'id' => $user->id,
			'avatar' => $user->avatar,
			'email' => $user->email,
			'name' => $user->name,
			'hash' => (int) $user->is_admin,
		];
		unset($user);
		return $this->response->withSuccess($list);
	}

	public function modifyInfo(Request $request) {
		$user = $this->model->getById(Auth::user()->id);
		$user->fill($request->only(
			'nick_name', 'website', 'weibo', 'github', 'description'
		));
		$user->save();
		return $this->response->withNoContent();
	}

	public function changeAvatar(Request $request) {
		$file = $request->file('file');
		if ($file->isValid()) {
			$ext = $file->getClientOriginalExtension();
			$realPath = $file->getRealPath();
			$type = $file->getClientMimeType();
			$filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
			$bool = Storage::disk('avatar')->put($filename, file_get_contents($realPath));
			if (!$bool) {
				abort(500, 'file move fail');
			}
			$user = $this->model->saveAvatar(Auth::user()->id, $filename);
			return $this->response->withSuccess($user);
		} else {
			abort(422, 'file upload fail');
		}
	}

	protected function getResourceCollection(Collection $collection) {
		return new UserCollection($collection->load(['comments' => function ($query) {
			return $query->withoutGlobalScope(StatusScope::class);
		}])->load(['approves' => function ($query) {
			return $query->withoutGlobalScope(StatusScope::class);
		}]));
	}

	protected function getResource(UserModel $collection) {
		return new User($collection);
	}
}
